
<template>
  <div>
    <Modal v-model="modal" :title="'创建'+titles" footer-hide  :z-index="1068" width="1150">
      <div v-if="modal">
        <div style="max-height: 70vh;overflow: auto;padding: 20px;">
          <div class="form-gourp">
            <span class="form-title">基本信息</span>
            <achieveform :lists="formlist1" :ainfo="info1" ref="form1"/>
          </div>

          <div class="form-gourp">
            <span class="form-title">详细信息</span>
            <achieveform :lists="formlist2" :ainfo="info2" ref="form2"/>
          </div>

          <div class="form-gourp" style="padding-bottom: 60px;">
            <span class="form-title">作者信息</span>

              <div style="width: 100%;margin-bottom: 40px;">
                <Button type="default" @click="newauthors" style="float: left;">创建作者</Button>
              </div>


              <Table
                  border
                  :columns="columns"
                  :data="authors"
                  ref="table"
              >
<!--              <template #type="{ row,index }">-->
<!--                <Select filterable v-model="row.type" placeholder="人员类型" transfer>-->
<!--                  <Option :value='1' :key='1'>校内人员</Option>-->
<!--                  <Option :value='2' :key='2'>校外人员</Option>-->
<!--                </Select>-->
<!--              </template>-->
              <template #name="{ row,index }">
                <div :class="getErrorName(row.name)">
                <Input v-model="row.name" placeholder="昵称" @on-change="changeTable(row,index)" show-word-limit :maxlength="32"></Input>
                <div class="ivu-form-item-error-tip1">昵称不能为空</div>
                </div>
              </template>
              <template #degree="{ row,index }">
                <div class="table-input-ok">
                <Input v-model="row.degree" placeholder="学历" @on-change="changeTable(row,index)"  show-word-limit :maxlength="32"></Input>
                <div class="ivu-form-item-error-tip1"></div>
                </div>
              </template>
              <template #role="{ row,index }">
                <div class="table-input-ok">
                <Select filterable v-model="row.role" placeholder="角色" transfer @on-change="changeTable(row,index)">
                  <Option :value='op.value' v-for="(op,i) in authorRoles"  :key="i">
                    {{op.label}}
                  </Option>
                </Select>
                <div class="ivu-form-item-error-tip1"></div>
                </div>
              </template>
              <template #company="{ row,index }">
                <div class="table-input-ok">
                  <Input v-model="row.company" placeholder="工作单位" @on-change="changeTable(row,index)"  show-word-limit :maxlength="64"></Input>
                  <div class="ivu-form-item-error-tip1"></div>
                </div>
              </template>
              <template #contribution="{ row,index }">
                <div :class="getError100(row.contribution)">
                  <Input v-model="row.contribution" placeholder="贡献率" @on-change="changeTable(row,index)" show-word-limit :maxlength="3"></Input>
                  <div class="ivu-form-item-error-tip1">贡献率是0~100的整数</div>
                </div>

              </template>
                <template #delbutn="{ row,index }">
                 <span @click="deletefun(index)">删除</span>
                </template>
            </Table>
          </div>

        </div>

        <div slot="footer" class="modal-footer-a">
          <Button type="default" @click="modal = false">取消</Button>
          <Button type="info" @click="submit" :loading="loading" style="margin: 0 10px;">确定</Button>
        </div>

      </div>



    </Modal>
  </div>
</template>

<script>
import {
  mapActions,
  mapState
} from 'vuex'


import {debounce} from "../../../libs/utils";
import achieveform from "./achieveform.vue";
import {addAchievement, getDirectionForSelect,getAInfo,editAchievement} from "../../../api/achievements";

import {formconfig} from "../achConfig";
export default {
  name: 'achieform',
  props: ['type','ainfo','close','tas'],
  components:{achieveform},
  data() {
    return {
      // 学术论文 a1 学术著作 a2 学术专利 a3 鉴定成果 a4 获奖成果 a5 软件著作 a6
      isValidate:true,//刚刚开始不校验作者信息了
      modal: false,
      fconfig:formconfig,
      info:this.ainfo,
      loading:false,
      info1:this.ainfo||{},
      info2:(this.ainfo && this.ainfo.detail)||{},
      formlist1:[
        {label:'著作编号',key:'no',type:'input',value:'',require:true},
        {label:'著作名称',key:'name',type:'input',value:'',require:true},
        {label:'著作类别',key:'level',type:'select',dictid:'zzlb',require:true},
        {label:'出版单位',key:'coontentCompany',type:'input',value:'',require:true},
        {label:'出版社级别',key:'level2',type:'select',dictid:'cbsjb',require:true},
        {label:'出版时间',key:'time',type:'date',require:true},//
        {label:'所属单位',key:'attribution',type:'input',value:'',require:true},
        {label:'项目来源',key:'origin',type:'select',dictid:'xmly',require:true},
        {label:'出版地',key:'region',type:'radio',options:[{label:'国内',value:'国内'},{label:'国外',value:'国外'}],require:true},
        {label:'封面图片',key:'imageUri',type:'uploadimg',value:'',require:true},
      ],
      formlist2:[
        {label:'学校署名',key:'school',type:'radio',options:[{label:'第一单位',value:'第一单位'},{label:'非第一单位',value:'非第一单位'}],require:true},
        {label:'统计年度',key:'year',type:'year',require:true},//
        {label:'PCT专利',key:'isPCT',type:'radio',options:[{label:'是',value:'是'},{label:'否',value:'否'}],require:true},
        {label:'翻译为外文',key:'istrans',type:'radio',options:[{label:'是',value:'是'},{label:'否',value:'否'}],require:true},
        {label:'ISBN号',key:'isbn',type:'input',value:'',require:true},
        {label:'CIP号',key:'cip',type:'input',value:'',require:true},
        {label:'上传附件',key:'fileinfo',type:'uploaddoc',value:'',require:true},
        {label:'备注内容',key:'desc',type:'textarea',require:true},
      ],
      columns:[ // 作者信息
        {type: 'index', width: 60, align: 'center'},
        // { title: '人员类型', slot: 'type', minWidth: 100 },
        { title: '昵称', slot: 'name', minWidth: 100 },
        { title: '学历', slot: 'degree', minWidth: 100 },
        { title: '承担角色', slot: 'role', minWidth: 100 },
        { title: '工作单位', slot: 'company', minWidth: 100 },
        { title: '贡献率(%)', slot: 'contribution', minWidth: 100 },
        { title: '操作', slot: 'delbutn', width: 60 },
      ],
      authors:[
        {name:'',type:1} // type 默认1 校内人员 ，2、校外人员'
      ],
      authorRoles:[],
      titles:'成就'

    }
  },
  watch: {
    modal: { //路由修改后init 页面
      handler: function(newv,oldv) {

        if(newv){
          this.init()
        }else {
          this.info1 = {}
          this.info2 = {}
          this.authors =  [{type:1}]
        }


        let key = (this.$route.query.page && Number(this.$route.query.page)) ||1
        this.titles = this.tas[key]

      },
      deep: true
    },
  },

  created() {


  },
  filters: {

  },
  computed: {
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {

  },
  methods: {
    deletefun(index){
     this.authors.splice(index, 1);
    },

    init(){
      let act = this.$route.query.page
      if(this.fconfig && this.fconfig['a'+act]){
        let form = this.fconfig['a'+act]
        this.formlist1 = form.formlist1
        this.formlist2 = form.formlist2
      }




      getDirectionForSelect('cgjs').then(res=>{
        this.authorRoles = res || []
      })

      this.getInfo()

    },
    changeTable(row,index){
      this.isValidate = false // 已经修改了，可以开始校验作者信息了
      let authos = JSON.parse(JSON.stringify(this.authors))
      authos[index] = row
      this.authors = authos

    },
    getInfo(){

      let id = this.ainfo.id
      if(!id) {
        this.info1 = {}
        this.info2 = {}
        this.authors =  [{type:1}]
        return
      }
      getAInfo(id).then(res=>{
        if(res.data.code===1){
          let info = res.data.data||{}

          if(info.imageUri) info.imageUri = JSON.parse(info.imageUri)

          let detailStr = info.detail
          let detail  = JSON.parse(detailStr)

          this.info1 = info
          this.info2 = detail
          this.authors = info.authors
        }
      })


    },

    formattime(value){
      if(!value) return ''
      const dateTime = new Date(value);
      const year = dateTime.getFullYear();
      const month = String(dateTime.getMonth() + 1).padStart(2, '0');
      const day = String(dateTime.getDate()).padStart(2, '0');
      const hours = String(dateTime.getHours()).padStart(2, '0');
      const minutes = String(dateTime.getMinutes()).padStart(2, '0');
      const seconds = String(dateTime.getSeconds()).padStart(2, '0');

      const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDateTime
    },

    clone(val){
      if (typeof val === 'object' && val !== null) {
        return JSON.parse(JSON.stringify(val))
      } else {
        return val
      }
    },

    validateForm(formRef) {
      return new Promise((resolve, reject) => {
        formRef.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            
            reject(new Error('表单校验失败'));
          }
        });
      });
    },


    submit() {
      this.isValidate = false
      let form1Promise = null
      let form2Promise = null
      if(this.$refs.form1 && this.$refs.form1.$refs && this.$refs.form1.$refs.formValidate){
         form1Promise = this.validateForm(this.$refs.form1.$refs.formValidate);
      }
      if(this.$refs.form2 && this.$refs.form2.$refs && this.$refs.form2.$refs.formValidate){
        form2Promise = this.validateForm(this.$refs.form2.$refs.formValidate);
      }

      let authors = this.authors||[]
      let authorsInfoFlag = ''

      this.authors.forEach(item=>{
        authorsInfoFlag += this.getErrorName(item.name)+this.getError100(item.contribution)
      })
      console.log('------authorsInfoFlag---',authorsInfoFlag)
      if(authorsInfoFlag.includes('ivu-form-item-error')){
        Promise.all([form1Promise, form2Promise])
        this.$Message.error('请完善信息')
        return
      }


      Promise.all([form1Promise, form2Promise])
      .then(() => {
        this.submitForms()
      })
      .catch((error) => {
        console.log(error)
        this.$Message.error('请完善信息！');
      });
    },


    submitForms(){


      let formValidate1 =  this.clone(this.$refs.form1.formValidate)
      let formValidate2 =  this.clone(this.$refs.form2.formValidate)
      formValidate2.year = formValidate1.year
      formValidate1.imageUri = JSON.stringify(formValidate1.imageUri) // 将图片信息 存储成字符串



      var authors = this.authors || [];

      let data = {
        ...formValidate1,
        detail:JSON.stringify(formValidate2),
        authors:authors,
        type:Number(this.$route.query.page) || 1
      }

      data.time = this.formattime(data.time)

      let title=data.id?'编辑':'创建'
      let mthod = data.id?editAchievement:addAchievement

      this.loading = true
      mthod(data).then(res => {
        let { code, message } = res.data
        if (code !== 1) {
          this.$Message.warning(message)
          return
        }else {
          this.$Message.success(`${title}成功`)
          if(this.close)this.close()
        }
      }).catch(() => {
        this.$Message.error(`${title}异常`)
      }).finally(() => {
        this.loading = false
        //this.addSlefExaminationLoding = false
      })





    },
    getError100(val){
      if(val+''==='null' || val+''==='undefined' || val+''===''){
        return 'table-input-ok'
      }


      const regex = /^(?:0|[1-9]\d?|100)$/;
      let flag =  regex.test(val);
      if(!flag){
        return 'ivu-form-item-error'
      }
      return 'table-input-ok'
    },
    getErrorName(val){
      if(this.isValidate){ // 刚刚开始不校验作者信息
        return 'table-input-ok'
      }

      if(val+''==='null' || val+''==='undefined' || val+''===''){
        return 'ivu-form-item-error'
      }
      return 'table-input-ok'

    },


    cancelModal(){

    },
    newauthors(){
      this.authors.push({type:1}) // 默认 校内人员
    }



  },

}
</script>
<style scoped>
.form-gourp{
  border: 1px solid var(--card-line-color);
  margin-bottom: 40px;
  position: relative;
  padding: 20px 10px;
}

.form-title{
  color: var(--default-color);
  font-weight: 700;
  position: absolute;
  top: -9px;
  left: 10px;
  background-color: var(--modal-bgcolor);
  display: inline-block;
  padding: 0 6px;
}
/deep/ .ivu-modal-body{
  padding: 0 !important;
}
.modal-footer-a{
  display: flex;
  justify-content: right;
  border-top:1px solid var(--card-line-color);
  padding: 10px;
}

.ivu-form-item-error-tip1{
  color: red;
  display: block;
  height:18px;
  margin-top: 0 !important;
}

.table-input-ok .ivu-form-item-error-tip1{
  opacity: 0;

}

.ivu-form-item-error , .table-input-ok{
  margin-top: 20px;
}



</style>
